package scli

import (
	"github.com/urfave/cli/v2"
)

type (
	cliCmd struct {
		app  *cli.App
		opts *Options
		ctx  *cli.Context
	}
)

func newCmd(opts ...Option) Cmd {
	help := &cli.Command{
		Name:    "help",
		Aliases: []string{"h"},
		Usage:   "idl2lang helper",
		Action: func(c *cli.Context) error {
			args := c.Args()
			if args.Present() {
				cli.ShowCommandHelpAndExit(c, args.First(), 1)
				return nil
			}
			cli.ShowAppHelpAndExit(c, 1)
			return nil
		},
	}
	cmd := &cliCmd{opts: &Options{
		commands: []*cli.Command{help},
	}}
	err := cmd.Init(opts...)
	if err != nil {
		return nil
	}
	return cmd
}

func (z *cliCmd) Init(options ...Option) error {
	z.app = cli.NewApp()
	z.app.Name = "idl2lang"
	z.app.Usage = "Plato 协议生成工具"
	z.app.UsageText = `
  _____    _ _ ___  _                   
 |_   _|  | | |__ \| |                  
   | |  __| | |  ) | | __ _ _ __   __ _ 
   | | / _· | | / /| |/ _· | ·_ \ / _· |
  _| || (_| | |/ /_| | (_| | | | | (_| |
 |_____\__,_|_|____|_|\__,_|_| |_|\__, |
                                   __/ |
                                  |___/ 
`

	//init options
	for _, o := range options {
		o(z.opts)
	}

	if len(z.opts.flags) > 0 {
		z.app.Flags = z.opts.flags
	}

	if len(z.opts.commands) > 0 {
		z.app.Commands = z.opts.commands
	}
	z.app.Action = z.cmdAction
	return nil
}

func (z *cliCmd) Parse(args []string) error {
	return z.app.Run(args)
}

func (z *cliCmd) GetString(name string) string {
	if z.ctx == nil {
		//TODO add error log
		return ""
	}
	return z.ctx.String(name)
}

func (z *cliCmd) GetBool(name string) bool {
	if z.ctx == nil {
		//TODO add error log
		return false
	}
	return z.ctx.Bool(name)
}

func (z *cliCmd) GetNumber(name string) int {
	if z.ctx == nil {
		//TODO add error log
		return 0
	}
	return z.ctx.Int(name)
}

func (z *cliCmd) cmdAction(ctx *cli.Context) error {
	z.ctx = ctx
	return nil
}
